package ua.com.softway.db;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TransactionFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        EntityManagerFactory entityManagerFactory = Persistence.getEntityManagerFactory();
        
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Persistence.setCurrentEntityManager(entityManager);
        
        EntityTransaction transaction = null;
        
        try {
            transaction = entityManager.getTransaction();
            
            transaction.begin();
            
            filterChain.doFilter(servletRequest, servletResponse);
            
            if (transaction.isActive()) {
                if (transaction.getRollbackOnly()) {
                    entityManager.clear();
                    transaction.rollback();
                } else {
                    entityManager.flush();
                    transaction.commit();
                }
            }
        } finally {
            if ( transaction != null && transaction.isActive() ) transaction.rollback();

            entityManager.close();
            Persistence.setCurrentEntityManager(null);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
